<template>
    <div class="card-wrap mb10 animate-on-enter">
        <a-space wrap>
            <a-button type="primary" :icon="h(PlusCircleOutlined)" @click="onAddRole">新增</a-button>
        </a-space>
    </div>
    <div class="card-wrap animate-on-enter animate-delay-1">
        <DataList ref="dataListRef" :columns="columns" :api="getRoleListApi" :delete-api="deleteRoleApi"
            @action="onAction" />
    </div>

    <!-- 新增/编辑角色弹窗 -->
    <a-modal v-model:open="openRoleModal" :title="formState.id ? '编辑角色' : '新增角色'" :footer="false">
        <a-form ref="formRef" :model="formState" :rules="rules" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }"
            @finish="onRoleSubmit">
            <a-form-item label="角色名称" name="name">
                <a-input v-model:value="formState.name" placeholder="请填写角色名称" />
            </a-form-item>
            <a-form-item label="角色描述" name="description">
                <a-textarea v-model:value="formState.description" placeholder="请填写角色描述" :rows="3" />
            </a-form-item>
            <a-form-item label="状态" name="status">
                <a-radio-group v-model:value="formState.status">
                    <a-radio :value="1">开启</a-radio>
                    <a-radio :value="0">禁用</a-radio>
                </a-radio-group>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                <a-button type="primary" html-type="submit">保存</a-button>
                <a-button style="margin-left: 10px" @click="openRoleModal = false">取消</a-button>
            </a-form-item>
        </a-form>
    </a-modal>

    <!-- 设置权限弹窗 -->
    <a-modal v-model:open="openPermissionModal" title="设置权限" width="600px" :footer="null">
        <!-- 创建人分组提示 -->
        <div v-if="currentRole && currentRole.is_founder === 1"
            style="margin-bottom: 16px; padding: 16px; background-color: #fff7e6; border: 1px solid #ffd591; border-radius: 6px; color: #d46b08;">
            <div style="font-size: 14px; margin-bottom: 8px; font-weight: 500;">👑 系统创建人分组</div>
            <div style="font-size: 13px; line-height: 1.5;">
                该角色为系统创建人分组，拥有系统最高权限，无需进行权限分配。
            </div>
        </div>
        <!-- 普通角色权限设置说明 -->
        <div v-else
            style="margin-bottom: 16px; padding: 12px; background-color: #f6f8fa; border-radius: 6px; color: #666;">
            <div style="font-size: 14px; margin-bottom: 8px;">💡 权限设置说明：</div>
            <div style="font-size: 13px; line-height: 1.5;">
                • 勾选菜单项表示该角色拥有对应的访问权限<br>
                • 父级菜单被勾选时，子级菜单会自动继承权限<br>
                • 请根据角色职责合理分配权限，确保系统安全
            </div>
        </div>
        <!-- 只有非创建人分组才显示权限树 -->
        <a-tree v-if="!currentRole || currentRole.is_founder !== 1" v-model:checkedKeys="checkedMenus"
            :tree-data="menuTreeData" checkable checkStrictly :default-expand-all="true"
            :field-names="{ children: 'children', title: 'title', key: 'id' }" />
        <a-space v-if="currentRole.is_founder != 1" style="margin-top: 40px;">
            <a-button type="primary" @click="onPermissionSubmit">确定</a-button>
            <a-button @click="openPermissionModal = false">取消</a-button>
        </a-space>
    </a-modal>
</template>
<script setup>
import { onMounted, ref, reactive, h } from 'vue'
import { message } from 'ant-design-vue'
import { PlusCircleOutlined } from '@ant-design/icons-vue'
import DataList from '@/components/DataList.vue'
import { getRoles, saveRole, deleteRole, getRoleMenus, getAllMenus, saveRolePermission } from '@/api/auth'

// 响应式数据
const dataListRef = ref()
const formRef = ref()
const openRoleModal = ref(false)
const openPermissionModal = ref(false)
const menuTreeData = ref([])
const checkedMenus = ref([])
const currentRole = ref(null)
// 表格列配置
const columns = [
    {
        title: '角色名称',
        dataIndex: 'name'
    },
    {
        title: '角色描述',
        dataIndex: 'description'
    },
    {
        title: '状态',
        dataIndex: 'status'
    },
    {
        title: '创建时间',
        dataIndex: 'created_at'
    },
    {
        title: '操作',
        type: 'action',
        options: [
            {
                title: '编辑',
                type: 'edit'
            },
            {
                title: '设置权限',
                type: 'permission'
            },
            {
                title: '删除',
                type: 'delete'
            }
        ]
    }
]

// 表单数据
const formState = reactive({
    id: '',
    name: '',
    description: '',
    status: 1
})

// 表单验证规则
const rules = {
    name: [
        {
            required: true,
            message: '请填写角色名称',
            trigger: 'change',
        }
    ]
}

// 生命周期
onMounted(() => {
    getMenus()
})

// 获取角色列表API
const getRoleListApi = () => {
    return getRoles()
}

// 删除角色API
const deleteRoleApi = (record) => {
    return deleteRole({ id: record.id })
}

// 获取菜单列表
function getMenus() {
    getAllMenus().then(res => {
        if (res.code == 200) {
            menuTreeData.value = res.result
        }
    })
}


// 新增角色
const onAddRole = () => {
    Object.assign(formState, {
        id: '',
        name: '',
        description: '',
        status: 1
    })
    openRoleModal.value = true
}

// 处理操作
const onAction = (item, record) => {
    if (item.type === 'edit') {
        Object.assign(formState, record)
        openRoleModal.value = true
    } else if (item.type === 'permission') {
        handleSetPermission(record)
    }
}

// 设置权限
function handleSetPermission(record) {
    currentRole.value = record
    getRoleMenus({ role_id: record.id }).then(res => {
        if (res.code == 200) {
            checkedMenus.value = res.result
        }

        openPermissionModal.value = true
    })
}


// 提交表单
function onRoleSubmit() {
    saveRole(formState).then(res => {
        if (res.code == 200) {
            message.success('保存成功')
            openRoleModal.value = false
            dataListRef.value.refreshData()
        }
    })

}


// 提交权限设置
function onPermissionSubmit() {

    const params = {
        id: currentRole.value.id,
        menu_ids: checkedMenus.value.checked
    }

    saveRolePermission(params).then(res => {
        if (res.code == 200) {
            message.success('权限设置成功')
            openPermissionModal.value = false
        }
    })
}
</script>
<style lang="scss" scoped></style>